package es.albarregas.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.albarregas.modelo.ModelFacade;
import es.albarregas.tools.Tools;

/**
 * Servlet implementation class ModifyLineaPedido
 */
@WebServlet("/ModifyLineaPedido")
public class ModifyLineaPedidoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String[] cantidades = request.getParameterValues("cantidad");
		String[] oidLinea = request.getParameterValues("oidLinea");
		
		int loopCantidad = 0;
		int loopOid = 0;
		
		if (cantidades != null && cantidades.length > 0){
			for(int i=0; i<cantidades.length; i++){
				//System.out.println("Cantidad "+cantidades[i]);
				//System.out.println("Oid "+oidLinea[i]);
				
				if (isNumeric(cantidades[i])){									
					loopOid = Integer.parseInt(oidLinea[i]);
					loopCantidad = Integer.parseInt(cantidades[i]);
					if (loopCantidad > 0){
						ModelFacade.modifyCantidadLinea(loopOid, loopCantidad);
					}
					else if(loopCantidad == 0){
						ModelFacade.deleteLineaPedido(loopOid);
					}
				}
				else {
					Tools.aniadirMensaje(request, "Cantidad incorrecta");
					break;
				}
			}
			
		}
		request.getRequestDispatcher(request.getParameter("pageid")).forward(request, response);

		
	}
	
	public static boolean isNumeric(String str) {
	  return str.matches("^[0-9]*$" );  //match a number with optional '-' and decimal.
	}

}
